package br.ufrj.dcc.smarthotel;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListAdapterImageTextMenu extends ArrayAdapter<JSONObject> {

	private final Activity context;
	private final JSONObject[] sightList;
	
	public ListAdapterImageTextMenu(Activity context, JSONObject[] sightList) {
		super(context, R.layout.tourmenu, sightList);
		this.context = context;
		this.sightList = sightList;
	}
	
	static class ViewHolder {
		public ImageView imageView;
		public TextView textView;
	}
	
	/***
	 * Metodo que retorna o item da lista de pontos tur�sticos
	 * @param position - Posicao na lista de pontos tur�sticos
	 */
	@Override
	public JSONObject getItem(int position) {
		return this.sightList[position];
	}

	/***
	 * Metodo que retorna o id do item da lista de pontos tur�sticos
	 * @param position - Posicao na lista de pontos tur�sticos
	 */
	@Override
	public long getItemId(int position) {
		long itemId = 0;
		try {
			itemId = (long) Integer.parseInt(this.sightList[position].get("id").toString());
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return itemId;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// ViewHolder will buffer the assess to the individual fields of the row
		// layout
		ViewHolder holder;
		
		// Recycle existing view if passed as parameter
		// This will save memory and time on Android
		// This only works if the base layout for all classes are the same
		View rowView;
		if (convertView == null) {
			LayoutInflater inflater = context.getLayoutInflater();
			rowView = inflater.inflate(R.layout.tourmenu, null, true);
			holder = new ViewHolder();
			holder.textView = (TextView) rowView.findViewById(R.id.sightName);
			holder.imageView = (ImageView) rowView.findViewById(R.id.sightMiniature);
			rowView.setTag(holder);
		} else {
			rowView = convertView;
			holder = (ViewHolder)rowView.getTag();
		}
		
		try {
			if(sightList[position].get("name").toString() != null) {
				holder.textView.setText(sightList[position].get("name").toString());
				holder.imageView.setImageBitmap(Util.getInstance(convertView.getContext()).downloadImage(sightList[position].get("miniatureURL").toString()));
			}
			else {
				holder.textView.setText("veio nulo");
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return rowView;
	}

}
